package com.mjf.ys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjf.ys.domain.ProductEntity;
import com.mjf.ys.enums.YSApiEnum;
import com.mjf.ys.mapper.YsProductMapper;
import com.mjf.ys.service.YsProductService;
import com.mjf.ys.util.YSSendUtil;
import com.mjf.ys.vo.ProductClassVO;
import com.mjf.ys.vo.ProductDetailVo;
import com.mjf.ys.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/6/8 00:51
 */
@Slf4j
@Service
public class YsProductServiceImpl extends ServiceImpl<YsProductMapper, ProductEntity> implements YsProductService {

    @Autowired
    private YSSendUtil  ysSendUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void asyncProduct() {
        String sendUrl = ysSendUtil.getSendUrl(YSApiEnum.YS_API_GOODS_DETAIL_LIST_URL);
        String detailUrl = ysSendUtil.getSendUrl(YSApiEnum.YS_API_GOODS_DETAIL_URL);
        Map<String, Object> resMap = new HashMap<>();
        log.info("商品同步，开始 {} ", sendUrl);
        resMap.put("pageSize", 500);
        resMap.put("totalCount", 10000);
        int i = 1;
        boolean  flag = true;
        List<ProductEntity> all = list();
        Map<String, Long> skuMap = all.stream().collect(Collectors.toMap(ProductEntity::getSkuCode,
            ProductEntity::getProductId, (v1, v2) -> v1));
        List<ProductEntity> resulList = new ArrayList<>();
        while (flag) {
            log.info(" 第 {} 页 ", i);
            resMap.put("pageIndex", i);
            try {
                String repsp = ysSendUtil.reqForResp(sendUrl, resMap);
                // 解析接口
                ProductVo productResult = JSON.parseObject(repsp, ProductVo.class);
                if (CollectionUtils.isEmpty(productResult.getData().getRecordList())) {
                    flag = false;
                }
                // 插入商品数据
                List<ProductEntity> productListData = productResult.getData().getRecordList().stream()
                    .filter(e -> StrUtil.isNotBlank(e.getProductId_code())
                        && StrUtil.isNotBlank(e.getProductId_detail_barCode())).map(p -> {
                        // 查询商品详情
                        MultiValueMap<String, String> productDetailParam = new LinkedMultiValueMap<>();
                        productDetailParam.add("id", p.getProductId());
                        productDetailParam.add("productApplyRangeId", p.getProductApplyRangeId());
                        String detailRepsp =
                            ysSendUtil.reqForGetWithParam(detailUrl, productDetailParam);
                        // 解析接口
                        ProductDetailVo detailVoResult = JSON.parseObject(detailRepsp, ProductDetailVo.class);
                        ProductEntity entry = new ProductEntity();
                        entry.setYsProductId(p.getProductId());
                        entry.setProductApplyRangeId(p.getProductApplyRangeId());
                        entry.setBarCode(p.getProductId_detail_barCode());
                        entry.setSkuCode(p.getProductId_code());
                        entry.setSkuName(p.getName());
                        entry.setStockUnit(p.getStockUnit());
                        entry.setBatchUnit(detailVoResult.getData().getDetail().getBatchUnit());
                        entry.setBatchPriceUnit(detailVoResult.getData().getDetail().getBatchPriceUnit());

                        if (StrUtil.isNotBlank(detailVoResult.getData().getDetail().getOutTaxrate())) {
                            entry.setTaxId(detailVoResult.getData().getDetail().getOutTaxrate());
                        }
                        if (StrUtil.isNotBlank(detailVoResult.getData().getUnit())) {
                            entry.setUnit(detailVoResult.getData().getUnit());
                        }
                        return entry;
                    }).collect(Collectors.toList());

                Map<String, List<ProductEntity>> map = productListData.stream().collect(Collectors.groupingBy(ProductEntity::getSkuCode));
                map.forEach((k, v) -> resulList.add(v.get(0)));
                i ++;
            } catch (Exception e) {
                log.error("商品同步异常", e);
                flag = false;
            }
        }
        if (CollectionUtils.isNotEmpty(resulList)) {
            resulList.forEach(e -> e.setProductId(skuMap.get(e.getSkuCode())));
            saveOrUpdateBatch(resulList);
        }
        log.info("商品同步结束,处理数据：{}", resulList.size());
    }

}
